Page({
    data: {
        imgList: [] // 存储图片临时路径
    },
    onShow() {
        console.log('[TRACE] 页面显示');
        this.checkLoginStatus();
    },

    // ====================== 登录状态检查 ======================  
    checkLoginStatus() {
        try {
            const userInfo = wx.getStorageSync('userInfo');

            // 新增用户名读取逻辑
            const userName = userInfo.name || '未知用户'; // 添加默认值

            if (!userInfo?.employee_number) {
                this.showLoginAlert();
                return;
            }

            this.setData({
                employeeNumber: userInfo.employee_number.trim(),
                userName: userName // 新增用户名存储
            }, );

        } catch (error) {
            console.error('存储读取失败:', error);
            this.showLoginAlert();
        }
    },

    showLoginAlert() {
        wx.showModal({
          title: '未登录',
          content: '请先登录后再使用该功能',
          confirmText: '去登录',
          cancelText: '返回首页', // 明确提示取消操作的含义
          success: (res) => {
            if (res.confirm) {
              wx.reLaunch({ url: '/pages/user/user' });
            } else if (res.cancel) {
              // 增加页面堆栈判断防止报错
              if (getCurrentPages().length > 1) {
                wx.navigateBack({ delta: 1 }); // 返回上一页
              } else {
                wx.reLaunch({ url: '/pages/home/home' }); // 无上一页时回首页
              }
            }
          },
          fail: (err) => {
            console.error('弹窗调用失败:', err);
          }
        });
      },

    // ====================== 用户信息 ======================
    initUserInfo() {
        console.log('[TRACE] 初始化用户信息');
        try {
            const userInfo = wx.getStorageSync('userInfo');
            if (!userInfo?.employee_number) {
                console.log('[WARN] 未找到用户信息，跳转登录');
                wx.redirectTo({
                    url: '/pages/login/login'
                });
                return;
            }

            this.setData({
                employeeNumber: userInfo.employee_number,
                deviceInfo: `${wx.getSystemInfoSync().model} ${wx.getSystemInfoSync().system}`
            }, () => {
                console.log('[TRACE] 用户信息更新完成');
            });

        } catch (err) {
            console.error('[ERROR] 用户信息初始化失败:', err);
        }
    },

    // 选择图片
    chooseImage() {
        const remain = 12 - this.data.imgList.length
        wx.chooseImage({
            count: remain,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: (res) => {
                this.setData({
                    imgList: this.data.imgList.concat(res.tempFilePaths)
                })
            }
        })
    },

    // 删除图片
    deleteImage(e) {
        const index = e.currentTarget.dataset.index
        const newList = this.data.imgList.filter((_, i) => i !== index)
        this.setData({
            imgList: newList
        })
    },

    // 预览图片
    previewImage(e) {
        const index = e.currentTarget.dataset.index
        wx.previewImage({
            current: this.data.imgList[index],
            urls: this.data.imgList
        })
    },

    // 核心生成PDF逻辑
    async generatePDF() {
        if (!this.data.imgList.length) {
            wx.showToast({
                title: '请先选择图片',
                icon: 'none'
            })
            return
        }

        wx.showLoading({
            title: '生成中...',
            mask: true
        })

        try {
            // 构造 multipart 数据
            const {
                data,
                contentType
            } = await this.buildMultipartData()

            // 发送请求
            const res = await this.uploadPDF(data, contentType)

            // 保存文件
            const filePath = `${wx.env.USER_DATA_PATH}/converted.pdf`
            await this.saveFile(res.data, filePath)

            // 打开文档
            wx.openDocument({
                filePath,
                showMenu: true,
                success: () => wx.showToast({
                    title: '生成成功'
                })
            })
        } catch (err) {
            console.error('生成失败', err)
            wx.showToast({
                title: '生成失败',
                icon: 'none'
            })
        } finally {
            wx.hideLoading()
        }
    },

    // 构建 multipart/form-data
    async buildMultipartData() {
        const boundary = `----WebKitFormBoundary${Math.random().toString(16)}`
        const parts = []

        // 添加图片部分
        for (const path of this.data.imgList) {
            const fileData = await this.readFile(path)
            const filename = path.split('/').pop()
            const header =
                `--${boundary}\r\n` +
                `Content-Disposition: form-data; name="fileInput"; filename="${filename}"\r\n` +
                `Content-Type: image/${filename.split('.').pop()}\r\n\r\n`
            parts.push(this.stringToBuffer(header))
            parts.push(fileData)
            parts.push(this.stringToBuffer('\r\n'))
        }

        // 添加其他参数
        const params = {
            fitOption: 'fillPage',
            colorType: 'color',
            autoRotate: 'true'
        }
        for (const [key, value] of Object.entries(params)) {
            const part =
                `--${boundary}\r\n` +
                `Content-Disposition: form-data; name="${key}"\r\n\r\n` +
                `${value}\r\n`
            parts.push(this.stringToBuffer(part))
        }

        // 结束标记
        parts.push(this.stringToBuffer(`--${boundary}--\r\n`))

        console.log('各部分字节长度:',
            parts.map(p => p.byteLength),
            '总长度:', this.mergeBuffers(parts).byteLength
        )

        return {
            data: this.mergeBuffers(parts),
            contentType: `multipart/form-data; boundary=${boundary}`
        }
    },

    // 工具方法：读取文件
    readFile(path) {
        return new Promise((resolve, reject) => {
            wx.getFileSystemManager().readFile({
                filePath: path,
                encoding: 'binary', // 使用合法编码参数
                success: (res) => {
                    // 将 binary 字符串转换为 ArrayBuffer
                    const buffer = new ArrayBuffer(res.data.length)
                    const view = new Uint8Array(buffer)
                    for (let i = 0; i < res.data.length; i++) {
                        view[i] = res.data.charCodeAt(i) & 0xff
                    }
                    resolve(buffer)
                },
                fail: reject
            })
        })
    },

    // 工具方法：字符串转ArrayBuffer
    stringToBuffer(str) {
        const buffer = new ArrayBuffer(str.length)
        const view = new Uint8Array(buffer)
        for (let i = 0; i < str.length; i++) {
            view[i] = str.charCodeAt(i)
        }
        return buffer
    },

    // 工具方法：合并多个ArrayBuffer
    mergeBuffers(buffers) {
        const validBuffers = buffers.map(buf => new Uint8Array(buf))
        const totalLength = validBuffers.reduce((acc, buf) => acc + buf.length, 0)
        const result = new Uint8Array(totalLength)
        let offset = 0
        validBuffers.forEach(buf => {
            result.set(buf, offset)
            offset += buf.length
        })
        return result.buffer
    },

    // 上传请求
    uploadPDF(data, contentType) {
        return new Promise((resolve, reject) => {
            const uploadTask = wx.request({
                url: 'https://spdf.10v.cc/api/v1/convert/img/pdf',
                method: 'POST',
                header: {
                    'Content-Type': contentType,
                    'Accept': '*/*'
                },
                data: data,
                responseType: 'arraybuffer',
                success: (res) => {
                    this.setData({
                        uploadProgress: 0
                    }) // 重置进度
                    resolve(res)
                },
                fail: (err) => {
                    this.setData({
                        uploadProgress: 0
                    })
                    reject(err)
                }
            })

            // 监听上传进度（需服务端支持进度返回）
            uploadTask.onProgressUpdate = (res) => {
                if (res.progress) {
                    this.setData({
                        uploadProgress: res.progress
                    })
                }
            }
        })
    },

    // 保存文件
    saveFile(data, path) {
        return new Promise((resolve, reject) => {
            wx.getFileSystemManager().writeFile({
                filePath: path,
                data: data,
                encoding: 'binary',
                success: resolve,
                fail: reject
            })
        })
    }

})